<template>
  <a-modal v-model:open="visible" :footer="null" :width="950" title="站位表 Excel 解析工具" @cancel="resetForm" @ok="handleOk">
    <a-form :model="formState" :rules="rules" layout="horizontal">
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="数据开始行" name="startRow">
            <a-input-number v-model:value="formState.startRow" :min="1" style="width: 100%" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="结束列字母" name="endColumn">
            <a-input v-model:value="formState.endColumn" placeholder="例如: H (将生成A-H列)" style="width: 100%" @change="handleColumnChange" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item>
        <a-button :loading="loading" type="primary" @click="generateTable"> 生成表格</a-button>
        <!--        <a-button style="margin-left: 10px" @click="loadSampleData" :loading="loading"> 加载示例数据</a-button>-->
      </a-form-item>
    </a-form>

    <a-divider v-if="showTable" />

    <div v-if="showTable">
      <a-alert :message="`已自动生成列: ${generatedColumns.join(', ')}`" show-icon style="margin-bottom: 16px" type="info" />

      <div style="overflow-x: auto">
        <a-table :columns="tableColumns" :data-source="tableData" :pagination="false" :scroll="{ x: 'max-content' }" bordered size="middle">
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex !== 'rowHeader'">
              <a-select
                v-model:value="record[column.dataIndex]"
                :options="getFilteredOptions(column.dataIndex, record[column.dataIndex])"
                style="width: 100%"
                @change="(value) => handleSelectChange(column.dataIndex, record, value)"
              />
            </template>
          </template>
        </a-table>
      </div>

      <div style="margin-top: 20px; text-align: center">
        <a-button :loading="submitting" type="primary" @click="validateAndSubmit"> 提交验证</a-button>
      </div>
    </div>
  </a-modal>
</template>

<script setup>
  import { computed, reactive, ref, watch } from 'vue';
  import { message } from 'ant-design-vue';
  import { useDictStore } from '/@/store/modules/system/dict.js';
  import { positionParseTempApi } from '/@/api/business/product/order/position-parse-temp-api.js';

  const customerCodeRef = ref();
  const visible = ref(false);
  const showModal = (customerCode) => {
    visible.value = true;
    customerCodeRef.value = customerCode;
    positionParseTempApi.getOne(1).then((res) => {
      loadSampleData(res.data);
    });
    let dataLabels = useDictStore()
      .getDictData('POSITION_FIELD')
      .map((item) => {
        return {
          value: item.dataValue,
          label: item.dataLabel,
        };
      });
    columnOptions.value.default = dataLabels;
  };

  const handleOk = () => {
    visible.value = false;
  };

  const formState = reactive({
    startRow: undefined,
    endColumn: undefined,
  });

  // 当前数据格式
  const currentDataFormat = reactive({
    startRow: undefined,
    endColumn: undefined,
    dataFormat: {},
  });

  // 生成从A到指定字母的列数组
  const generatedColumns = computed(() => {
    if (!formState.endColumn) return [];
    const endChar = formState.endColumn.toUpperCase();
    if (!/^[A-Z]$/.test(endChar)) return [];

    const columns = [];
    for (let i = 65; i <= endChar.charCodeAt(0); i++) {
      columns.push(String.fromCharCode(i));
    }
    return columns;
  });

  const rules = {
    startRow: [
      { required: true, message: '请输入数据开始行', trigger: 'blur' },
      { type: 'number', min: 1, message: '开始行必须大于0', trigger: 'blur' },
    ],
    endColumn: [
      { required: true, message: '请输入结束列字母', trigger: 'blur' },
      {
        validator: (_, value) => {
          if (!value) return Promise.reject();
          if (!/^[A-Za-z]$/.test(value)) {
            return Promise.reject('请输入单个大写字母 (A-Z)');
          }
          return Promise.resolve();
        },
        trigger: 'blur',
      },
    ],
  };

  const loading = ref(false);
  const submitting = ref(false);
  const showTable = ref(false);
  const tableColumns = ref([]);
  const tableData = ref([]);
  const columnOptions = ref({
    default: [],
  });

  // 已选择的选项（除了"useless"）
  const selectedValues = ref(new Set());

  // 获取过滤后的选项（实现除了"useless"其他不能重复选择）
  const getFilteredOptions = (column, currentValue) => {
    return columnOptions.value.default.map((option) => {
      // "useless"选项始终可用
      if (option.value === 'useless') return option;

      // 当前选中的选项可用
      if (option.value === currentValue) return option;

      // 未被选择的选项可用
      if (!selectedValues.value.has(option.value)) return option;

      // 其他情况禁用
      return {
        ...option,
        disabled: true,
      };
    });
  };

  // 处理列字母变化
  const handleColumnChange = () => {
    formState.endColumn = formState.endColumn.toUpperCase();
  };

  const loadSampleData = (sampleData = null) => {
    // 如果没传参数，使用默认示例数据
    if (!sampleData) {
      return;
    }

    // 设置表单值
    formState.startRow = sampleData.startRow;
    formState.endColumn = sampleData.endColumn;
    sampleData.dataFormat = JSON.parse(sampleData.dataFormat);
    // 生成表格
    generateTable();

    // 在表格生成后回填数据
    setTimeout(() => {
      // 更新当前数据格式
      Object.assign(currentDataFormat, sampleData);

      // 更新表格数据
      if (tableData.value.length > 0) {
        const row = tableData.value[0];
        selectedValues.value.clear();

        Object.keys(sampleData.dataFormat).forEach((key) => {
          const col = String.fromCharCode(65 + parseInt(key));
          const value = sampleData.dataFormat[key];
          row[col] = value;

          // 更新已选择的值（排除"未知"）
          if (value !== '未知') {
            selectedValues.value.add(value);
          }
        });
      }
    }, 500);
  };

  // 生成表格结构
  const generateTable = () => {
    loading.value = true;
    selectedValues.value.clear();
    currentDataFormat.dataFormat = {};

    // 模拟异步操作
    setTimeout(() => {
      try {
        // 使用自动生成的列
        const columns = [...generatedColumns.value];

        // 更新数据格式
        currentDataFormat.startRow = formState.startRow;
        currentDataFormat.endColumn = formState.endColumn;

        // 生成表头
        tableColumns.value = [
          {
            title: '行号',
            dataIndex: 'rowHeader',
            key: 'rowHeader',
            width: 80,
            align: 'center',
            fixed: 'left',
          },
          ...columns.map((col, index) => ({
            title: col,
            dataIndex: col,
            key: col,
            width: 100,
            // 初始化dataFormat
            customIndex: index,
          })),
        ];

        // 只生成一行数据，行号为用户输入的起始行
        tableData.value = [
          {
            key: 0,
            rowHeader: `${formState.startRow}`,
            ...columns.reduce((acc, col) => {
              acc[col] = undefined; // 初始值为空
              return acc;
            }, {}),
          },
        ];

        showTable.value = true;
      } catch (error) {
        message.error('生成表格时出错: ' + error.message);
      } finally {
        loading.value = false;
      }
    }, 500);
  };

  // 处理下拉选择变化
  const handleSelectChange = (column, record, value) => {
    // 更新已选择的值
    const oldValue = record[column];

    // 移除旧值（如果不是"useless"）
    if (oldValue && oldValue !== 'useless') {
      selectedValues.value.delete(oldValue);
    }

    // 添加新值（如果不是"useless"）
    if (value && value !== 'useless') {
      selectedValues.value.add(value);
    }

    // 更新当前数据格式
    const columnIndex = tableColumns.value.findIndex((col) => col.dataIndex === column) - 1;
    if (columnIndex >= 0) {
      currentDataFormat.dataFormat[columnIndex] = value;
    }
  };

  // 验证并提交表单
  const validateAndSubmit = () => {
    submitting.value = true;

    // 检查所有下拉框是否已选择
    const hasEmptyValues = tableData.value.some((row) => {
      return Object.keys(row).some((key) => {
        return key !== 'rowHeader' && key !== 'key' && !row[key];
      });
    });

    if (hasEmptyValues) {
      submitting.value = false;
      message.error('请确保所有下拉框都已选择值');
      return;
    }

    let param = currentDataFormat;
    param['customerCode'] = customerCodeRef.value;
    param['dataFormat'] = JSON.stringify(currentDataFormat.dataFormat);
    console.log(param);
    positionParseTempApi.update(param).then((res) => {
      message.success('提交成功');
      resetForm();
    });
  };

  // 监听表格数据变化，更新currentDataFormat
  watch(
    tableData,
    (newVal) => {
      if (newVal.length > 0) {
        const row = newVal[0];
        tableColumns.value.forEach((col, index) => {
          if (index > 0 && row[col.dataIndex]) {
            currentDataFormat.dataFormat[index - 1] = row[col.dataIndex];
          }
        });
      }
    },
    { deep: true }
  );

  const resetForm = () => {
    // 1. 重置表单输入
    formState.startRow = undefined;
    formState.endColumn = undefined;

    // 2. 重置当前数据格式
    currentDataFormat.startRow = undefined;
    currentDataFormat.endColumn = undefined;
    currentDataFormat.dateFormat = {};

    // 3. 重置表格相关状态
    showTable.value = false;
    tableColumns.value = [];
    tableData.value = [];

    // 4. 重置已选择的值
    selectedValues.value.clear();

    // 5. 重置加载状态
    loading.value = false;
    submitting.value = false;

    visible.value = false;
  };

  // 在模板中添加重置按钮
  // <a-button style="margin-left: 10px" @click="resetForm">重置表单</a-button>

  defineExpose({
    showModal,
  });
</script>

<style scoped>
  /* 可以添加自定义样式 */
  pre {
    background: #f6f6f6;
    padding: 12px;
    border-radius: 4px;
    overflow-x: auto;
  }
</style>
